<template>
	<view class="ipt-box">
		<view class="card-box" @click="show = true">
			<view class="item" v-for="(item, index) in 8" :key="index">
				{{ displayChar(index) }}
			</view>
		</view>

		<u-keyboard ref="uKeyboard" mode="car" :show="show" @backspace="backspace" @cancel="cancelForm"
			@confirm="confirmMethod" @change="changeForm" />
	</view>
</template>

<script>
	export default {
		props: {
			modelValue: String,
		},
		emits: ["update:modelValue"],
		data() {
			return {
				show: false,
				content: "",
				list: [],
			};
		},
		methods: {

			displayChar(index) {
				if (this.list[index]) return this.list[index];
				if (index === 0) return "省";
				if (index === 7) return "新";
				return "";
			},


			changeForm(e) {
				const len = this.list.length;
				if (len >= 8) {
					return this.cancelForm();
				}

				let isValid = true;
				if (len === 0) {

					isValid = /[\u4e00-\u9fa5]/.test(e);
				} else if (len === 1) {

					isValid = /^[A-Z]$/.test(e);
				}

				if (isValid) {
					this.list.push(e.toString());
				} else {
					uni.showToast({
						icon: "none",
						title: "非法输入",
					});
				}

				console.log("当前输入：", this.list);
			},

			backspace() {
				this.list.pop();
			},

			confirmMethod() {
				this.submit();
			},

			cancelForm() {
				this.submit();
			},

			submit() {
				this.content = this.list.join("");
				this.show = false;
				this.$emit("iptValue", this.content);
				this.$emit("update:modelValue", this.content); // 新增：同步 v-model 值
			},
		},
	};
</script>

<style lang="scss" scoped>
	.card-box {
		width: 100%;
		display: grid;
		grid-template-columns: repeat(8, 1fr);
		gap: 6rpx;

		.item {
			width: 70rpx;
			height: 70rpx;
			border-radius: 10rpx;
			border: 1rpx solid #eee;
			font-size: 28rpx;
			color: #222;
			display: flex;
			justify-content: center;
			align-items: center;

			&:nth-child(1) {
				color: #fff;
				background: #2979ff;
			}

			&:last-child {
				color: #fff;
				background: #19be6b;
			}
		}
	}
</style>